﻿using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using XRM.Security.DataAccess.Enums;
using XRM.Security.DataAccess.Models;
using XRM.Security.WebUI.Enums;
using XRM.Security.WebUI.Helpers;
using XRM.Security.WebUI.Models.Department;
using XRM.Security.WebUI.Models.UserRegister;

namespace XRM.Security.WebUI.Controllers
{
    [Authorize]
    public class DepartmentController : BaseController
    {
        [Authorize(Roles = "Administrator, StructDepartmentViewer, StructDepartmentEditor")]
        public ActionResult Index()
        {
            var departments = DepartmentRepository.GetAll(x => x.IsDeleted == false)
                .Select( s => new DepartmentListItem
                    {
                        Id = s.DepartmentId,
                        Name = s.Name,
                        Addresses = s.DepartmentAddresses.Select(addr => addr.Address).ToList(),
                        UsersCount = s.Users.Count(),
                        WorkedUsersCount = s.Users.Count(x => x.Status == (int)UserStatus.Work),
                        RequestsOpenCount = s.RequestParams.Where(x => !x.RequestWorkKind.CloseDate.HasValue).Count()
                    })
                .ToList();

            return View(departments);
        }
        
        [HttpGet]
        [Authorize(Roles = "Administrator, StructDepartmentViewer, StructDepartmentEditor")]
        public ActionResult Edit(int? id)
        {
            DepartmentModel model = new DepartmentModel(id != null ? DepartmentRepository.Get(id) : null);
            if ((id != null) && (model.Id == null))
                throw new HttpException(404, "Структурное подразделение не найдено");
            else if ((id == null) && (!Permission.AllowDepartmentEdit()))
                throw new HttpException(404, "Структурное подразделение не найдено");

            model.ReadOnly = !Permission.AllowDepartmentEdit();
            foreach (DepartmentAddressModel item in model.AddressesList)
            {
                item.CanDelete = (!UserRegisterRepository.GetAll(x => x.DepartmentAddressId == item.Id.Value).Any()) && (!RequestWorkKindParamRepository.GetAll(x => x.DepartmentAddressId == item.Id.Value).Any());
            }
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Administrator, StructDepartmentEditor")]
        public ActionResult Edit(DepartmentModel model)
        {
            if (!ModelState.IsValid)
            {
                ShowAlert(AlertType.Error, GetModelErrors());
                return View(model);
            }

            string checkValue = model.Name;
            if (DepartmentRepository.Get(x => (x.Name.ToLower().Equals(checkValue) && (x.DepartmentId != model.Id) && (!x.IsDeleted))) != null)
            {
                ShowAlert(AlertType.Error, string.Format("Подразделение с названием '{0}' уже существует", model.Name));
                return View(model);
            }
            
            Department department = new Department();
            if (model.IsEdit)
            {
                department = DepartmentRepository.Get(model.Id);
            }

            department.Name = model.Name;
            department.DepartmentAddresses.Where(x => !model.AddressesList.Any(x2 => x.DepartmentAddressId.Equals(x2.Id ?? -1))).ToList().ForEach(a => DepartmentAddressRepository.Delete(DepartmentAddressRepository.Get(a.DepartmentAddressId)));

            foreach (var item in model.AddressesList)
            {
                DepartmentAddress address = department.DepartmentAddresses.SingleOrDefault(x => x.DepartmentAddressId.Equals(item.Id ?? -1));
                if (address != null)
                    address.Address = item.Address;
                else
                    department.DepartmentAddresses.Add(new DepartmentAddress { Address = item.Address });
            }

            if (model.IsEdit)
            {
                DepartmentRepository.Update(department);
                ShowAlert(AlertType.Success, "Подразделение отредактировано успешно");
            }
            else
            {
                DepartmentRepository.Add(department);
                ShowAlert(AlertType.Success, "Подразделение создано успешно");
            }
            
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "Administrator, StructDepartmentEditor")]
        public ActionResult Delete(int id)
        {
            Department department = DepartmentRepository.Get(id);
            if (department == null)
                throw new System.Web.Http.HttpResponseException(HttpStatusCode.BadRequest);

            department.IsDeleted = true;
            DepartmentRepository.Update(department);
            ShowAlert(AlertType.Success, "Подразделение удалено успешно");
            return RedirectToAction("Index");
        }

        [HttpPost]
        public JsonResult AddressList(int? departmentId)
        {   
            return Json(UserRegisterModel.GetDepartmentAddressList(DataManager, departmentId).ToJsonObject(), JsonRequestBehavior.AllowGet);
        }
    }
}
